<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Controller\Api\V1;

use App\Constant\ApiCodeEnum;
use App\Controller\AbstractController;
use App\Exception\ValidateException;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Qbhy\HyperfAuth\Authenticatable;
use Qbhy\HyperfAuth\AuthGuard;
use Qbhy\HyperfAuth\AuthManager;

/**
 * 基类控制器.
 */
class CController extends AbstractController
{
    private array $pageInfo = [];

    /**
     * 获取当前登录用户ID.
     */
    public function uid(): int
    {
        $guard = $this->guard();

        return $guard->check() ? $guard->user()->getId() : 0;
    }

    /**
     * 获取登录用户信息.
     */
    public function user(): ?Authenticatable
    {
        $guard = $this->guard();

        return $guard->check() ? $guard->user() : null;
    }

    /**
     * 获取授权守卫.
     *
     * @return AuthGuard|AuthManager|mixed
     */
    public function guard()
    {
        return auth('jwt');
    }

    /**
     * 自定义控制器验证器.
     * @param mixed ...$arg
     */
    protected function validate(...$arg)
    {
        $validator = di()->get(ValidatorFactoryInterface::class)->make(...$arg);
        if ($validator->fails()) {
            throw new ValidateException($validator->errors()->first());
        }
    }

    protected function setPageInfo(array $pageInfo): static
    {
        $this->pageInfo = $pageInfo;
        return $this;
    }

    protected function success(array $data, RequestInterface $request, int|string $code = ApiCodeEnum::SUCCESS_DEFAULT)
    {
        $message = '';
        if (stripos($code, '|') !== false) {
            $arr = explode('|', $code);
            $message = $arr[1];
            $code = $arr[0];
        }
        $result = [
            'code' => $code,
            'msg' => $message,
            'data' => $data,
            'request_id' => $request->input('request_id'),
        ];
        if ($this->pageInfo) {
            $result['page_info'] = $this->pageInfo;
        }
        return response()->json($result);
    }
}
